﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using WinFormMapDemo.Model;
namespace WinFormMapDemo
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [ComVisible(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            mapBrowser.ScriptErrorsSuppressed = true; //禁用错误脚本提示
            mapBrowser.IsWebBrowserContextMenuEnabled = false; // 禁用右键菜单
            mapBrowser.WebBrowserShortcutsEnabled = false; //禁用快捷键
            mapBrowser.AllowWebBrowserDrop = false; // 禁止文件拖动
            mapBrowser.ObjectForScripting = this;
        }

        /// <summary>
        /// 向窗体显示信息（JS调用）
        /// </summary>
        /// <param name="message"></param>
        public void ShowMessage(string message,string caption,string messageType="")
        {
            MessageBoxIcon icon = MessageBoxIcon.Information;
            bool result = Enum.TryParse<MessageBoxIcon>(messageType, out icon);
            MessageBox.Show(message, caption, MessageBoxButtons.OK, icon);
        }

        /// <summary>
        /// 更新经纬度（JS调用）
        /// </summary>
        /// <param name="obj">坐标对象</param>
        public void UpdateLngLat(dynamic obj)
        {
            double lat= obj.lat;
            double lng= obj.lng;
            this.txtLat.Text = lat.ToString();
            this.txtLng.Text = lng.ToString();


            //Console.WriteLine(lngLat.ToString());
        }
        /// <summary>
        /// 更新地址（JS调用）
        /// </summary>
        /// <param name="address"></param>
        public void UpdateAddress(string address)
        {
            this.txtAddress.Text = address;
            AddDeviceForm.UpdateAddress(address);
        }
        /// <summary>
        /// 添加设备（JS调用）
        /// </summary>
        /// <param name="obj">坐标对象</param>
        public void AddDevice(dynamic obj)
        {


            LngLat lngLat = new LngLat
            {
                Latitude = obj.lat,
                Longitude = obj.lng
            };
            string defaultDeviceName = "设备" + listView1?.Items.Count.ToString() ?? "0";
            
            //设备添加回调
            var addDeviceCallback = new Func<DeviceInfo, int>((d) =>
            {
                DeviceInfo deviceInfo = d;
                this.listView1.Items.Add(new ListViewItem()
                {
                    Tag = deviceInfo,
                    ImageIndex = 0,
                    Text = deviceInfo.DeviceNo + "-" + deviceInfo.DeviceName,
                    
                });
                //在地图中添加标志物
                this.mapBrowser.Document.InvokeScript("addMarker", new object[] {
                    deviceInfo.DeviceNo,
                    deviceInfo.DevicePosition.Longitude,
                    deviceInfo.DevicePosition.Latitude
                });
                return 0;
            });
            AddDeviceForm form = AddDeviceForm.Create(lngLat, this.txtAddress.Text, defaultDeviceName,addDeviceCallback);
            form.ShowDialog();
        }

        /// <summary>
        /// 根据设备坐标获取设备信息
        /// </summary>
        /// <param name="lng">经度</param>
        /// <param name="lat">纬度</param>
        /// <returns></returns>
        public string GetDeviceInfo(double lng,double lat)
        {
            foreach (ListViewItem item in this.listView1.Items)
            {
                var deviceInfo = item.Tag as DeviceInfo;
                if(deviceInfo == null)
                {
                    continue;
                }
                if(Math.Abs(deviceInfo.DevicePosition.Longitude -lng) <=0.000001 && 
                    Math.Abs(deviceInfo.DevicePosition.Latitude -lat)<=0.000001)
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(deviceInfo);
                }
                
            }
            return "";

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var  dom =  Application.StartupPath + @"\www\index.html";
            this.mapBrowser.Navigate(dom);
            
        }

        /// <summary>
        /// 刷新地图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.mapBrowser.Refresh();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(listView1.SelectedItems.Count ==0)
            {
                btnRemove.Enabled = false;
                return;
            }
            btnRemove.Enabled = true;
            ListViewItem viewItem = listView1.SelectedItems[0];
            DeviceInfo deviceInfo = viewItem?.Tag as DeviceInfo;
            if (viewItem ==null || deviceInfo == null || deviceInfo == null)
            {
                return;
            }
            this.mapBrowser.Document.InvokeScript("showDeviceDetails", new object[]{ deviceInfo.DeviceNo});

        }

        /// <summary>
        /// 移除设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            ListViewItem viewItem = listView1.SelectedItems[0];
            DeviceInfo deviceInfo = viewItem?.Tag as DeviceInfo;
            if (viewItem == null || deviceInfo == null || deviceInfo == null)
            {
                ShowMessage("获取设备信息失败", "系统提示", "Error");
                return;
            }
            string result = mapBrowser.Document.InvokeScript("removeDeviceInfo", new object[] { deviceInfo.DeviceNo }).ToString();
            if (string.IsNullOrEmpty(result) || result == "False")
            {
                ShowMessage("移除设备失败", "系统提示", "Error");
            }
            else
            {
                listView1.SelectedItems[0].Remove();
            }
            
        }

        /// <summary>
        /// 激活ListView中的设备项目（JS调用）
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        public void ActiveDeviceInfo(string deviceNo)
        {
            if(string.IsNullOrEmpty(deviceNo))
            {
                return;
            }
            foreach (ListViewItem item in listView1.Items)
            {
                var deviceInfo = item.Tag as DeviceInfo;
                if(deviceInfo == null)
                {
                    continue;
                }

                if(deviceInfo.DeviceNo == deviceNo)
                {

                     item.Selected = true;
                }
                else
                {
                     item.Selected = false;
                }
            }
            listView1.HideSelection = false;
            listView1.Focus();
        }
    }
}
